// 视差映射
Shader "PJD/Scerne/ParallaxMapping"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _NormalTex("NormalTex",2D) = "bump" {}
        _ParallaxTex("ParallaxTex",2D) = "white" {} // 高度图

        _ParallaxStengtn("ParallaxStengtn",float) = 1
        _ParallaxAmount("ParallaxAmount",int) = 10  //循环次数
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float3 normal : NORMAL;
                float4 tangent : TANGENT;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
                float3 worldNormal : TEXCOORD2;
                float3 worldTangent : TEXCOORD3;
                float3 worldBitangent : TEXCOORD4;
                float3 worldPos : TEXCOORD5;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            sampler2D _NormalTex;
            sampler2D _ParallaxTex;
            float _ParallaxStengtn;
            float _ParallaxAmount;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);

                // 法线 切线 副切线
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                o.worldTangent = UnityObjectToWorldDir(v.tangent);
                float sign = v.tangent.w; // * GetOddNegativeScale基于缩放的变化值
                o.worldBitangent = cross(o.worldNormal,o.worldTangent) * sign;
                // 世界坐标
                o.worldPos = mul(unity_ObjectToWorld,v.vertex);

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                //基于视差映射: T= viewDir.xy*(height/viewDir.z)
                //带偏移上线的视差映: T=viewDir.xy*height

                float2 offset = 0;
                float3 viewDir = normalize(i.worldPos - _WorldSpaceCameraPos.xyz);
                // 世界空间转到切线空间
                viewDir = mul(float3x3(i.worldTangent,i.worldBitangent,i.worldNormal),viewDir);

                float parallaxTex = 1 - tex2D(_ParallaxTex,i.uv).r;

                float height = parallaxTex;

                // 这里用陡峭视差映射
                float curDepth = 0; // 计算到的深度


                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}
